package com.binhthuan.catechist.client.menu;

import com.google.gwt.event.shared.HandlerRegistration;
import com.smartgwt.client.types.VisibilityMode;
import com.smartgwt.client.widgets.layout.SectionStack;
import com.smartgwt.client.widgets.layout.SectionStackSection;
import com.smartgwt.client.widgets.tree.events.HasLeafClickHandlers;
import com.smartgwt.client.widgets.tree.events.LeafClickHandler;

public class StackMenu extends SectionStack implements HasLeafClickHandlers {

    /**
     *  
     */
    public StackMenu() {
        super();

        setVisibilityMode(VisibilityMode.MUTEX);
        setAnimateSections(true);
        setWidth100();
        setHeight100();
        setHeaderHeight(32);
        setShowExpandControls(false);
    }

    public StackMenu(StackMenuSection... sections) {
        this();

        if (sections != null) {
            addSections(sections);
        }
    }

    public void addSection(StackMenuSection section) {
        if (section != null) {
            this.addSection((SectionStackSection) section);
        }
    }

    public void addSections(StackMenuSection... sections) {
        if (sections != null) {
            for (int i = 0; i < sections.length; i++) {
                if (sections[i].getItemCount() > 0) {
                    this.addSection(sections[i]);
                }
            }
        }
    }

    @Override
    public HandlerRegistration addLeafClickHandler(LeafClickHandler handler) {
        if (getHandlerCount(com.smartgwt.client.widgets.tree.events.LeafClickEvent.getType()) == 0) {
            setupMenuItemClickEvent(handler);
        }
        return doAddHandler(handler, com.smartgwt.client.widgets.tree.events.LeafClickEvent.getType());
    }

    private void setupMenuItemClickEvent(LeafClickHandler handler) {
        SectionStackSection[] children = this.getSections();
        StackMenuSection child = null;
        for (int i = 0; i < children.length; i++) {
            if (children[i] instanceof StackMenuSection) {
                child = (StackMenuSection) children[i];
                child.addLeafClickHandler(handler);
            }
        }
    }
}
